package com.example.zhaoping.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Component
public class TokenUtil {
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000; //过期时间：24小时

    private static final Logger logger = LoggerFactory.getLogger(TokenUtil.class);
    /**
     * 密钥
     */
    private static final String SECRET = "jwt_secret";

    //生成密钥
    public static String sign(Long userId, Map<String, Object> info){
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    //将Id保存到token里面
                    .withAudience(String.valueOf(userId))
                    //存放自定义数据
                    .withClaim("info",info)
                    //token过期时间
                    .withExpiresAt(date)
                    //token的密钥
                    .sign(algorithm);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据token获取自定义数据info
     * @param token
     * @return
     * */
    public Map<String, Object> getInfo(String token) {
        try {
            return JWT.decode(token).getClaim("info").asMap();
        }catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 根据token获取userId
     * @param token
     * @return
     * */
    public static int getUserId(String token) {
        try {
            String userId = JWT.decode(token).getAudience().get(0);
            return Integer.parseInt(userId);
        }catch (JWTDecodeException e) {
            return 0;
        }
    }
    public int getUserId1(String token) {
        try {
            String userId = JWT.decode(token).getAudience().get(0);
            return Integer.parseInt(userId);
        }catch (JWTDecodeException e) {
            return 0;
        }
    }

    /**
     * 校验token
     * @param token
     * @return
     * */
    public boolean checkSign(String token) {
        if(StringUtils.isEmpty(token)) return false;
        try {
            Algorithm algorithm  = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            int id = TokenUtil.getUserId(token);
            logger.info("token验证通过：[id="+id+", info="+jwt.getClaim("info")+", 过期时间="+jwt.getExpiresAt()+"]");
            return true;
        }catch (JWTVerificationException e) {
            throw new TokenException(401,"身份验证已过期，请重新登录！");
        }
    }

//    public String getRole(String token){
//
//    }

//    //验证访问权限
//    public Result<?> authorization(String token, String requestURI){
//        if(this.checkSign(token)){
//            int id = this.getUserId(token);
//            String[] urlList = requestURI.split("/");
//            Authorization authorization = new Authorization();
//            return authorization.authorization(id,urlList[1],requestURI);
//        }else{
//            return new Result<>(Constants.CODE_400,"身份验证失败，请重新登录！",null);
//        }
//    }

}
